import { PluginOption } from "vite"

type Props = {
  exclude?: string[];
  less?: string[];
  scss?: string[];
  sass?: string[];
  isVue?: boolean;
}

const transform = (files: string[], code: string): string => {
  const globalPath = files.map(item => `${process.cwd()}/${item}`);
  const importCode = globalPath.map(item => `@import "${item}";\n`);
  return `${importCode}${code}`;
}

export default function globalPreload({ exclude = [], less, scss, sass, isVue = false }: Props): PluginOption {
  return {
    name: 'vite-plugin-css-global',
    enforce: 'pre',
    transform(code: string, id: string) {
      exclude.push("node_modules");
      const reg = new RegExp(`(${exclude.join(")|(")})`);
      if (isVue) {
        const styleReg = /<style.*?lang=\"(.+?)\".*?>(.+?)<\/style>/gs;
        const matches = [...code.matchAll(styleReg)];
        let res: string = "";
        if (matches.length) {
          for (let match of matches) {
            res = code.replace(match[0], match[0].replace(match[2], () => {
              switch (match[1].trim()) {
                case "less":
                  if (less && less.length) {
                    return transform(less, match[2]);
                  }
                  return match[2];
                case "scss":
                  if (scss && scss.length) {
                    return transform(scss, match[2]);
                  }
                  return match[2];
                case "sass":
                  if (sass && sass.length) {
                    return transform(sass, match[2]);
                  }
                  return match[2];
                default:
                  return match[2];
              }
            }))
          }
          return res || code;
        }
        return code;
      }
      if (less && less.length) {
        if (id.endsWith(".less")) {
          if (reg.test(id)) {
            return code
          }
          return transform(less, code);
        }
      }
      if (scss && scss.length) {
        if (id.endsWith(".scss")) {
          if (reg.test(id)) {
            return code
          }
          return transform(scss, code);
        }
      }
      if (sass && sass.length) {
        if (id.endsWith(".sass")) {
          if (reg.test(id)) {
            return code
          }
          return transform(sass, code);
        }
      }
    }
  }
}
